import datetime
import os
import time

import pyautogui
import cv2
import numpy as np
import redis
import win32gui
from paddleocr import PaddleOCR

from constants import windowTitle, walletToolHeight, walletUserInfoWidth

## QQ窗口的位置和宽高
positionX = 0
positionY = 0
windowWidth = 0
windowHeight = 0


# 右上角关闭按钮的位置和宽高
closeBtnLeft = 0
closeBtnTop = 0
closeWidth = 0
closeHeight = 0

# 查看领取详情的位置和宽高
detailLeft = 0
detailTop = 0
detailWidth = 0
detailHeight = 0
ocr = PaddleOCR(use_angle_cls=True, lang='ch')

redText = ""

findRedEnvelope = False

def get_window_geometry(title_keyword: str):
    """
    根据窗口标题关键词获取窗口的位置和大小。

    :param title_keyword: 窗口标题中的关键字（支持模糊匹配）
    :return: (left, top, width, height) 或 None 如果未找到窗口
    """

    def enum_handler(hwnd, results):
        if win32gui.IsWindowVisible(hwnd):
            title = win32gui.GetWindowText(hwnd)
            if title_keyword.lower() in title.lower():
                rect = win32gui.GetWindowRect(hwnd)
                left, top, right, bottom = rect
                width = right - left
                height = bottom - top
                results.append((left, top, width, height))

    results = []
    win32gui.EnumWindows(enum_handler, results)
    return results[0] if results else None

# 获取窗口位置
def init_position():
    global positionX, positionY,windowWidth,windowHeight
    window_info = get_window_geometry(windowTitle)
    if window_info:
        left, top, width, height = window_info
        positionX = left
        positionY = top
        windowWidth = width
        windowHeight = height
        print(f"窗口位置: ({left}, {top}), 尺寸: ({width}x{height})")
        screenshot(left,top,width,height,"window")
        return width, height,width,height
    else:
        print("未找到目标窗口")
    return None

# 截屏
def screenshot(x:int, y:int,width:int,height:int,fileName: str):
    base_dir = r"d:\redpackage"
    img = pyautogui.screenshot(region=(x,y,width,height))
    img_path = os.path.join(base_dir, f"{fileName}.png")
    img.save(img_path)


def init():
    init_position()
    # 计算红包的宽高
    global walletLeft, walletTop, walletWidth, walletHeight
    walletLeft = positionX+int(windowWidth/2)-160
    walletTop = positionY+int(windowHeight/2)-240
    walletWidth = 160*2
    walletHeight = 240*2
    screenshot(walletLeft,walletTop,walletWidth,walletHeight,'package')
    # 关闭按钮
    global closeBtnLeft, closeBtnTop, closeWidth, closeHeight
    closeBtnLeft = positionX + int(windowWidth / 2) + int(walletWidth / 2) - 27
    closeBtnTop = positionY + int(windowHeight / 2) - int(walletHeight / 2) + 8
    screenshot(closeBtnLeft, closeBtnTop, walletToolHeight, walletToolHeight, 'close')
    closeWidth = walletToolHeight
    closeHeight = walletToolHeight

    # 查看领取详情
    global detailWidth,detailHeight,detailLeft,detailTop,detailHeight
    detailWidth = 100
    detailHeight = 36
    detailLeft = positionX + int(windowWidth / 2) - 40
    detailTop = positionY + int(windowHeight / 2) + int(walletHeight / 2) - 60
    screenshot(detailLeft, detailTop, detailWidth, detailHeight,  'detail')
    

def screenshot1():
    img = pyautogui.screenshot(region=(positionX, positionY, windowWidth, windowHeight))
    img_np = np.array(img)
    return cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)

def find_and_click_red_envelope(r):
    stopSeconds = r.get("stopSeconds")
    global findRedEnvelope,redText
    image = screenshot1()
    result = ocr.ocr(image, cls=True)
    flag = False
    for line in result:
        if line is None:
            break
        for box, (text, prob) in line:
            if "拼手气红包" in text and prob > 0.7:
                if True:
                    redText = text
                    print(f"识别到红包: {text}, 置信度: {prob}")
                    # 计算点击位置
                    x1, y1 = box[0]
                    x2, y2 = box[2]
                    x, y = int((x1 + x2) / 2)+positionX, int((y1 + y2) / 2)+positionY
                    print(f"等待：{stopSeconds}")
                    time.sleep(int(stopSeconds))
                    pyautogui.click(x, y)
                    print(f"点击红包位置: ({x}, {y})")
                    flag = True
                    findRedEnvelope = True
                break
        if not flag:
            findRedEnvelope = False
            pyautogui.scroll(-400)
            pyautogui.scroll(30)

def close(folder):
    pyautogui.click(closeBtnLeft+int(closeWidth/2), closeBtnTop+int(closeHeight/2))
    print("关闭了")
    send_request(folder)
    pyautogui.sleep(0.2)
    pyautogui.scroll(-1*windowHeight)
    pyautogui.scroll(30)

from skimage.metrics import structural_similarity as compare_ssim
def is_similar(img1_path, img2_path, similarity_threshold=0.95):
    # 用 OpenCV 读取图片
    img1 = cv2.imread(img1_path)
    img2 = cv2.imread(img2_path)
    print(img1_path)
    print(img2_path)
    # 转灰度图（SSIM要求灰度）
    img1_gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
    img2_gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)

    # 计算结构相似度（返回值范围 [-1, 1]，越接近1越相似）
    score, _ = compare_ssim(img1_gray, img2_gray, full=True)

    print(f"相似度得分：{score}")

    return score >= similarity_threshold

def detail_and_click_red_envelope():
    x1 = detailLeft+int(detailWidth/2)
    y1 = detailTop+int(detailHeight/2)
    pyautogui.moveTo(x1, y1)
    pyautogui.click(x1, y1)
    pyautogui.click(x1, y1)
    screenshot(detailLeft, detailTop, detailWidth, detailHeight, 'detail')
    print(f"点击查看领取详情位置: ({x1}, {y1})")
    time.sleep(0.1)
    #  先滑动到最底部，在滑动到最上面
    for i in range(1, 10):
        pyautogui.scroll(300*-1)
    for i in range(1, 10):
        pyautogui.scroll(300*1)


    # 截图第一张
    base_dir = r"d:\redpackage"
    folder = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    save_dir = os.path.join(base_dir, folder)
    os.makedirs(save_dir, exist_ok=True)
    img = pyautogui.screenshot(region=(walletLeft, walletTop + walletToolHeight, walletWidth,walletHeight - walletToolHeight))
    img_path = os.path.join(save_dir, f"{1}.png")
    img.save(img_path)
    prev_image_path = img_path

    ## 后续的几张
    for i in range(2, 15):
        if i == 2:
            pyautogui.scroll((2 * walletUserInfoWidth+ 45) * -1)
            pyautogui.scroll((2 * walletUserInfoWidth+ 45) * -1)
            pyautogui.scroll(40 * -1)
        elif i == 3:
            pyautogui.scroll((2 * walletUserInfoWidth + 45) * -1)
            pyautogui.scroll((2 * walletUserInfoWidth + 45) * -1)
            pyautogui.scroll(74 * -1)
        elif i == 4:
            pyautogui.scroll((2 * walletUserInfoWidth + 45) * -1)
            pyautogui.scroll((2 * walletUserInfoWidth + 45) * -1)
            pyautogui.scroll(72 * -1)



        elif i == 5:
            pyautogui.scroll((2 * walletUserInfoWidth + 45) * -1)
            pyautogui.scroll((2 * walletUserInfoWidth + 45) * -1)
        elif i == 6:
            pyautogui.scroll((2 * walletUserInfoWidth + 45) * -1)
            pyautogui.scroll((2 * walletUserInfoWidth + 45) * -1)
        elif i == 7:
            pyautogui.scroll((2 * walletUserInfoWidth + 45) * -1)
            pyautogui.scroll((2 * walletUserInfoWidth + 45) * -1)
        elif i == 8:
            pyautogui.scroll((2 * walletUserInfoWidth + 45) * -1)
            pyautogui.scroll((2 * walletUserInfoWidth + 45) * -1)
        elif i == 9:
            pyautogui.scroll((2 * walletUserInfoWidth + 45) * -1)
            pyautogui.scroll((2 * walletUserInfoWidth + 45) * -1)
        elif i == 10:
            pyautogui.scroll((2 * walletUserInfoWidth + 45) * -1)
            pyautogui.scroll((2 * walletUserInfoWidth + 45) * -1)
        elif i == 11:
            pyautogui.scroll((2 * walletUserInfoWidth + 45) * -1)
            pyautogui.scroll((2 * walletUserInfoWidth + 45) * -1)
        elif i == 12:
            pyautogui.scroll((2 * walletUserInfoWidth + 45) * -1)
            pyautogui.scroll((2 * walletUserInfoWidth + 45) * -1)
        elif i == 13:
            pyautogui.scroll((2 * walletUserInfoWidth + 45) * -1)
            pyautogui.scroll((2 * walletUserInfoWidth + 45) * -1)
        else:
            pyautogui.scroll(5 * walletUserInfoWidth * -1)

        img = pyautogui.screenshot(region=(walletLeft, walletTop + walletToolHeight, walletWidth,  walletHeight - walletToolHeight))
        img_path = os.path.join(save_dir, f"{i}.png")
        current_image_path = img_path
        img.save(img_path)
        # 比较相似度
        if current_image_path and is_similar(prev_image_path, current_image_path):
            print("🚩 已经滚动到底部，停止截图")
            os.remove(current_image_path)
            close(folder)
            break
        else:
            prev_image_path = img_path
            time.sleep(1)
        if i == 14:
            close(folder)

import threading
import requests
def start(r):
    pyautogui.scroll(-300)
    pyautogui.scroll(30)
    global findRedEnvelope
    ## 查找红包
    find_and_click_red_envelope(r)
    if findRedEnvelope:
        # 点击红包的查看详情
        detail_and_click_red_envelope()

def send_request(batchId):
    try:
        requests.post("http://localhost:8080/send", json={"batchId": batchId})
    except Exception as e:
        print(f"请求失败: {e}")

    # 开启后台线程执行请求
    threading.Thread(target=send_request, daemon=True).start()

    print("主程序继续执行，不等待接口返回")

# 主函数
if __name__ == "__main__":
    init()
    # 连接redis
    r = redis.Redis(host='localhost', port=6379, decode_responses=True)
    while True:
        parse = r.get("parse")
        print(f"是否许需要解析的判断：{parse}")
        if parse=="0":
            # 暂停解析
            print('暂停解析，睡眠5秒')
            time.sleep(5)
        else:
            print("=============================================================================================================================")
            try:
                start(r)
            except Exception as e:
                print("error:",e)